package com.xmzs.web.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xmzs.common.chat.domain.request.ChatProcessRequest;
import com.xmzs.common.chat.entity.chat.BaseChatCompletion;
import com.xmzs.common.chat.entity.chat.ChatCompletion;
import com.xmzs.common.chat.utils.TikTokensUtil;
import com.xmzs.common.core.domain.model.LoginUser;
import com.xmzs.common.core.exception.base.BaseException;
import com.xmzs.common.satoken.utils.LoginHelper;
import com.xmzs.system.domain.SysUser;
import com.xmzs.system.mapper.SysUserMapper;
import com.xmzs.web.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;


/**
 * @author hncboy
 * @date 2023/3/22 19:41
 * 聊天相关业务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final SysUserMapper sysUserMapper;

    @Override
    public ResponseBodyEmitter chatProcess(ChatProcessRequest chatProcessRequest) {
        return new ResponseBodyEmitter(0L);
    }

    @Override
    public void deductToken(int tokens) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser ==null){
            throw new BaseException("用户未登录！");
        }
        SysUser sysUser = sysUserMapper.selectById(loginUser.getUserId());
        if(sysUser != null){
            int token = sysUser.getTokens() - tokens;
            // 余额不为负数
            if(token<1){
                token = 0;
            }
            sysUserMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getTokens, token)
                    .eq(SysUser::getUserId, loginUser.getUserId()));
        }
    }


}
